
/**
 * @ProjectName: 
 * @Copyright: 2014 lisheng  All Right Reserved.
 * @address: toughheart@163.com
 * @date: 2015年1月13日 下午9:32:11
 * @Description: 本内容未经本人允许禁止使用、转发.
 */
 
package com.ls.fw.data.search.impl.lucene.server;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ls.fw.data.search.impl.lucene.bean.SearchCondition;
import com.ls.fw.data.search.impl.lucene.server.base.AbstractBaseServer;


/**
 * 
 * @author lisheng
 * @date 2015年1月13日 下午9:32:11
 * @version V1.0 
 */
public abstract class AbstractMutilServer<T> extends AbstractBaseServer implements MutilServer<T>{

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public long count(List<LuceneServer> serverlist, final SearchCondition searchCondition){
		if(serverlist == null || serverlist.isEmpty()){
			return 0;
		}
		final AtomicInteger total = new AtomicInteger(0);
		if(serverlist!=null && !serverlist.isEmpty()){
			final CountDownLatch latch = new CountDownLatch(serverlist.size());
			final ExecutorService exec = Executors.newFixedThreadPool(serverlist.size());
			long start = System.currentTimeMillis();
			final SearchCondition sc = (SearchCondition) searchCondition.clone();
			for (final LuceneServer luceneServer : serverlist) {
				exec.execute(new Runnable() {
					
					@Override
					public void run() {
						IndexSearcher searcher = luceneServer.acquire();
						try {
							int count = (int) count(searcher, sc);
							total.addAndGet(count);
						} catch (Exception e) {
							e.printStackTrace();
						} finally{
							latch.countDown();
							luceneServer.release(searcher);
						}
					}
				});
			}
			exec.shutdown();
			try {
				latch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			long ends = System.currentTimeMillis();
	        logger.info("本次统计总数耗时:"+(ends-start)+"ms");
		}
		return total.intValue();
	}
	
	

	@Override
	public List<IndexReader> getIndexReaders(final List<LuceneServer> list) {
		List<IndexReader> searcherlist = new ArrayList<IndexReader>(list.size());
		for (LuceneServer server : list) {
			searcherlist.add(server.getIndexReader());
		}
		return searcherlist;
	}
	
	
}
